package yxy.game.pm2.module.godBeast;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.equipdata;
import yxy.cherry.data.bean.therion;
import yxy.cherry.data.bean.therionskill;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.GodBeastEquipPosition;
import yxy.game.pm2.bean.Item;
import yxy.game.pm2.bean.currency.CurrencyType;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.message.PickedGodBeastMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.PackageHandle;

import java.util.*;

/**
 * @author wrs
 * @description 神兽处理类
 * @since 2022-05-31
 */
public class PickedGodBeastHandle {

    /**
     * 激活神兽
     *
     * @param playerCode
     * @param godBeast
     */
    public void activateGodBeast(String playerCode, GodBeast godBeast, PickedGodBeastMessage.PickedGodBeastUnlockResponse.Builder response) {
        try {
            therion therion = DataCenter.getData(godBeast.getCode(), therion.class);
            Collection<Currency> currencies = Currency.create(therion.getCosttype(), therion.getCostid(), therion.getCostnum());
            new CurrencyHandle().cost(playerCode, CCReason.神兽槽, currencies); //消耗神兽令

            PickedGodBeastModule module = PickedGodBeastModule.get(playerCode);
            HashMap<String, GodBeast> gbs = module.getGbs();

            therion activated = DataCenter.getData(godBeast.getCode() + 1, therion.class);
            godBeast.setCode(activated.getId());
            godBeast.setName(activated.getName());
            godBeast.setType(activated.getType());
            godBeast.setAttack(activated.getAttack());
            godBeast.setDefense(activated.getDefense());
            godBeast.setLife(activated.getLife());
            godBeast.setOpen(true); //神兽解锁
            godBeast.setLevel(activated.getLevel());
            //神兽激活后，技能等级依然为0,装备为空

            gbs.replace(String.valueOf(godBeast.getType()), godBeast);
            module.set(); //将激活的神兽，保存到redis

            for (GodBeast value : module.getGbs().values()) {
                response.addGbs(getGodBeasts(playerCode, value));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 神兽升级
     *
     * @param playerCode
     * @param godBeast
     * @param response
     */
    public void godBeastLevelUp(String playerCode, GodBeast godBeast, PickedGodBeastMessage.PickedGodBeastLevelUpResponse.Builder response) {
        PickedGodBeastModule module = PickedGodBeastModule.get(playerCode);
        HashMap<String, GodBeast> gbs = module.getGbs();

        //神兽升级，神兽名称、技能等级、装备、解锁标志不变
        therion activated = DataCenter.getData(godBeast.getCode() + 1, therion.class);
        godBeast.setCode(activated.getId());
        godBeast.setAttack(activated.getAttack());
        godBeast.setDefense(activated.getDefense());
        godBeast.setLife(activated.getLife());
        godBeast.setLevel(activated.getLevel());

        gbs.put(String.valueOf(godBeast.getType()), godBeast);
        module.set(); //将激活的神兽，保存到redis

        for (GodBeast value : module.getGbs().values()) {
            response.addGbs(getGodBeasts(playerCode, value));
        }
    }

    /**
     * 获取神兽槽信息
     *
     * @param playerCode
     * @param response
     */
    public Result getGodBeastInfo(String playerCode, PickedGodBeastMessage.PickedGodBeastInfoResponse.Builder response) {
        try {
            PickedGodBeastModule module = PickedGodBeastModule.get(playerCode);

            for (GodBeast godBeast : module.getGbs().values()) {

                PickedGodBeastMessage.GodBeasts.Builder builder = PickedGodBeastMessage.GodBeasts.newBuilder(); //神兽基本信息

                int code = godBeast.getCode();
                therion data = DataCenter.getData(code, therion.class);

                Currency currency = Item.get(playerCode, CurrencyType.CT_物品, data.getCostid()[0]);
                if (currency != null && currency.getNumber() >= data.getCostnum()[0] && !godBeast.isOpen()) {  //背包有神兽令,神兽未解锁
                    builder.setIsActivate(true); //神兽可激活
                }

                //神兽是否最高等级
                builder.setIsUpperLevel(godBeast.getLevel() == godBeast.getMaxLevel());

                //技能是否最高等级
                builder.setIsUpperSkill(godBeast.getSkillLevel() == getGodBeastSkillMaxLevel(godBeast.getType()));

                builder.setCode(godBeast.getCode());
                builder.setName(godBeast.getName());
                builder.setUnlock(godBeast.isOpen()); //神兽是否解锁
                builder.setLevel(godBeast.getLevel());
                builder.setSkillLevel(godBeast.getSkillLevel()); //初始技能等级为0
                builder.setIsBattle(godBeast.isBattle()); //是否上阵

                //神兽装备
                for (int i = 0; i < godBeast.getGodBeastEquips().length; i++) {
                    PickedGodBeastMessage.Equip.Builder equipBuilder = PickedGodBeastMessage.Equip.newBuilder();
                    PickedGodBeastMessage.Property.Builder propertyBuilder = PickedGodBeastMessage.Property.newBuilder();
                    GodBeastEquip godBeastEquip = godBeast.getGodBeastEquips()[i];
                    if (godBeastEquip == null) { //装备初始锁定
                        builder.addEquips(PickedGodBeastMessage.Equip.newBuilder());
                        continue;
                    }
                    equipdata equipdata = DataCenter.getData(godBeastEquip.getId(), equipdata.class);
                    equipBuilder.setCode(godBeastEquip.getId());
                    equipBuilder.setType(equipdata.getPosition()); //装备部位
                    equipBuilder.setLevel(equipdata.getQuality()); //装备品质，等级
                    equipBuilder.setStar(equipdata.getStar()); //装备星级

                    equipBuilder.setStrengthenLevel(godBeastEquip.getStrengthenLevel());//装备强化等级

                    if (equipdata.getAttributetype() == 1) {
                        propertyBuilder.setAttack(equipdata.getAttributenum()); //攻击
                    } else if (equipdata.getAttributetype() == 2) {
                        propertyBuilder.setLife(equipdata.getAttributenum()); //生命
                    } else if (equipdata.getAttributetype() == 3) {
                        propertyBuilder.setDefense(equipdata.getAttributenum()); //防御
                    }
                    equipBuilder.setProperty(propertyBuilder); //装备属性
                    builder.addEquips(equipBuilder);
                }

                PickedGodBeastMessage.Property.Builder property = PickedGodBeastMessage.Property.newBuilder(); //神兽攻防血
                PickedGodBeastMessage.Property.Builder proper = getProperty(godBeast, property);
                builder.setProperty(proper);

                PickedGodBeastMessage.Property.Builder nextProperty = PickedGodBeastMessage.Property.newBuilder(); //神兽下一级攻防血
                PickedGodBeastMessage.Property.Builder nextProper = getNextProperty(godBeast, nextProperty);
                builder.setNextProperty(nextProper);

                response.addGbs(builder);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.Success;
    }

    /**
     * 封装神兽下一级的攻防血属性，包括装备
     *
     * @param nextProperty
     * @return
     */
    private PickedGodBeastMessage.Property.Builder getNextProperty(GodBeast godBeast, PickedGodBeastMessage.Property.Builder nextProperty) {
        Map<String, therion> allData = DataCenter.getAllData(therion.class);
        GodBeast next = new GodBeast();
        for (therion therion : allData.values()) {
            if (therion.getType() == godBeast.getType() && therion.getLevel() == godBeast.getLevel() + 1) {
                next.setCode(therion.getId());
                next.setType(therion.getType());
                next.setName(therion.getName());
                next.setLevel(therion.getLevel());
                next.setOpen(godBeast.isOpen());
                next.setAttack(therion.getAttack());
                next.setDefense(therion.getDefense());
                next.setLife(therion.getLife());
                next.setGodBeastEquips(godBeast.getGodBeastEquips());
                break;
            }
        }
        return getProperty(next, nextProperty);
    }

    /**
     * 封装神兽当前的攻防血属性，包括装备
     *
     * @param godBeast
     * @param property
     * @return
     */
    private PickedGodBeastMessage.Property.Builder getProperty(GodBeast godBeast, PickedGodBeastMessage.Property.Builder property) {
        //神兽基础属性
        int attack = godBeast.getAttack();
        int defense = godBeast.getDefense();
        int life = godBeast.getLife();

        for (GodBeastEquip godBeastEquip : godBeast.getGodBeastEquips()) {
            //穿戴装备
            if (godBeastEquip != null) {
                if (godBeastEquip.getAttributetype() == 1) { //攻击
                    attack += godBeastEquip.getAttributenume();
                } else if (godBeastEquip.getAttributetype() == 2) { //生命
                    life += godBeastEquip.getAttributenume();
                } else if (godBeastEquip.getAttributetype() == 3) { //防御
                    defense += godBeastEquip.getAttributenume();
                }
            }
        }

        property.setAttack(attack);
        property.setDefense(defense);
        property.setLife(life);

        return property;
    }

    /**
     * 神兽槽信息封装
     *
     * @param godBeast
     * @return
     */
    public PickedGodBeastMessage.GodBeasts.Builder getGodBeasts(String playerCode, GodBeast godBeast) {
        PickedGodBeastMessage.GodBeasts.Builder godBeastBuilder = PickedGodBeastMessage.GodBeasts.newBuilder();
        PickedGodBeastMessage.Property.Builder propertyBuilder = PickedGodBeastMessage.Property.newBuilder();
        PickedGodBeastMessage.Property.Builder nextPropertyBuilder = PickedGodBeastMessage.Property.newBuilder();
        PickedGodBeastMessage.Equip.Builder equipBuilder = PickedGodBeastMessage.Equip.newBuilder();

        try {

            int code = godBeast.getCode();
            therion data = DataCenter.getData(code, therion.class);

            Currency currency = Item.get(playerCode, CurrencyType.CT_物品, data.getCostid()[0]);
            if (currency != null && currency.getNumber() >= data.getCostnum()[0] && !godBeast.isOpen()) {  //背包有神兽令,神兽未解锁
                godBeastBuilder.setIsActivate(true); //神兽可激活
            }
            godBeastBuilder.setCode(godBeast.getCode());
            godBeastBuilder.setName(godBeast.getName());
            godBeastBuilder.setUnlock(godBeast.isOpen());
            godBeastBuilder.setLevel(godBeast.getLevel());
            godBeastBuilder.setIsBattle(godBeast.isBattle());

            if (godBeast.getLevel() == godBeast.getMaxLevel()) { //神兽是否最高等级
                godBeastBuilder.setIsUpperLevel(true);
            } else {
                godBeastBuilder.setIsUpperLevel(false);
            }
            if (godBeast.getSkillLevel() == getGodBeastSkillMaxLevel(godBeast.getType())) { //技能是否最高等级
                godBeastBuilder.setIsUpperSkill(true);
            } else {
                godBeastBuilder.setIsUpperSkill(false);
            }

            godBeastBuilder.setProperty(getProperty(godBeast, propertyBuilder));//神兽当前属性（攻防血）
            godBeastBuilder.setNextProperty(getNextProperty(godBeast, nextPropertyBuilder));//神兽下一级属性（攻防血）

            //神兽装备属性（攻防血）
            for (int i = 0; i < godBeast.getGodBeastEquips().length; i++) {
                GodBeastEquip godBeastEquip = godBeast.getGodBeastEquips()[i];
                if (godBeastEquip == null) {
                    godBeastBuilder.addEquips(PickedGodBeastMessage.Equip.newBuilder());
                    continue;
                }
                equipBuilder.setCode(godBeastEquip.getId());
                equipBuilder.setType(godBeastEquip.getPosition()); //装备部位
                equipBuilder.setLevel(godBeastEquip.getQuality()); //装备品质，等级
                equipBuilder.setStar(godBeastEquip.getStar()); //装备星级
                equipBuilder.setStrengthenLevel(godBeastEquip.getStrengthenLevel());//强化等级

                if (godBeastEquip.getAttributetype() == 1) {
                    propertyBuilder.setAttack(godBeastEquip.getAttributenume()); //攻击
                } else if (godBeastEquip.getAttributetype() == 2) {
                    propertyBuilder.setLife(godBeastEquip.getAttributenume()); //生命
                } else if (godBeastEquip.getAttributetype() == 3) {
                    propertyBuilder.setDefense(godBeastEquip.getAttributenume()); //防御
                }
                equipBuilder.setProperty(propertyBuilder); //装备属性
                godBeastBuilder.addEquips(equipBuilder);
            }

            //神兽技能等级
            godBeastBuilder.setSkillLevel(godBeast.getSkillLevel());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return godBeastBuilder;
    }

    /**
     * 神兽最高等级
     *
     * @param type 神兽类型
     * @return
     */
    static public int getGodBeastMaxLevel(int type) {
        Map<String, therion> allData = DataCenter.getAllData(therion.class);
        int maxLevel = -1;
        for (therion therion : allData.values()) {
            if (therion.getType() == type && therion.getLevel() > maxLevel) {
                maxLevel = therion.getLevel();
            }
        }
        return maxLevel;
    }

    /**
     * 神兽技能最高等级
     *
     * @param type 神兽类型
     * @return
     */
    static public int getGodBeastSkillMaxLevel(int type) {
        Map<String, therionskill> allData = DataCenter.getAllData(therionskill.class);
        int maxLevel = -1;
        for (therionskill therionskill : allData.values()) {
            if (therionskill.getType() == type && therionskill.getLevel() > maxLevel) {
                maxLevel = therionskill.getLevel();
            }
        }
        return maxLevel;
    }

    /**
     * 技能升级，神兽等级是否满足
     *
     * @param godBeast
     * @param skillLevel 当前技能等级
     * @return
     */
    public boolean isNeedLevel(GodBeast godBeast, int skillLevel) {
        boolean flag = false;
        therionskill now = getTherionSkill(godBeast, skillLevel);
        if (now != null && godBeast.getLevel() >= now.getNeedlevel()) { //神兽等级大于或等于 升级需要的等级
            flag = true;
        }
        return flag;
    }

    /**
     * 获取技能
     *
     * @param godBeast
     * @param skillLevel
     * @return
     */
    public therionskill getTherionSkill(GodBeast godBeast, int skillLevel) {
        Map<String, therionskill> allData = DataCenter.getAllData(therionskill.class);
        therionskill target = null;
        for (therionskill therionskill : allData.values()) {
            if (therionskill.getType() == godBeast.getType() && therionskill.getLevel() == skillLevel) {
                target = therionskill;
                break;
            }
        }
        return target;
    }

    /**
     * 技能升级资源消费是否满足
     *
     * @param godBeast
     * @param skillLevel
     * @return
     */
    public boolean checkCost(String playerCode, GodBeast godBeast, int skillLevel) {
        therionskill therionskill = getTherionSkill(godBeast, skillLevel);
        Collection<Currency> currencies = Currency.create(therionskill.getCosttype(), therionskill.getCostid(), therionskill.getCostnum());
        return new CurrencyHandle().costCheck(playerCode, currencies);
    }

    /**
     * 神兽替换装备
     *
     * @param playerCode
     * @param godBeast      神兽
     * @param equipPosition 装备位置
     * @param equipid       装备ID
     * @return
     */
    public Result ChangeEquip(String playerCode, GodBeast godBeast, GodBeastEquipPosition equipPosition, int equippos, int equipid) throws Exception {
        GodBeastEquip godBeastEquip = godBeast.getGodBeastEquips(equipPosition);
        if (godBeastEquip != null) { //装备栏中有装备
            if (equipid == godBeastEquip.getId()) {
                return Result.Success;
            }
            if (godBeastEquip.getId() > 0) {
                equipdata equipdata = DataCenter.getData(godBeastEquip.getId(), equipdata.class);
                if (equipdata == null) {
                    return Result.DataError;
                }
            }
        }
        if (equipid > 0) {
            //查看背包
            Currency item = Item.get(playerCode, CurrencyType.CT_装备, equipid);
            if (item == null || item.getNumber() < 1) {
                return Result.EquipNotExisted; //背包中没有这个装备
            }
            Item.minus(playerCode, CurrencyType.CT_装备, equipid, 1);
        }

        //脱下的装备放回背包,脱下前获取当前部位的强化等级
        if (godBeastEquip != null && godBeastEquip.getId() > 0) {
            int strengthenLevel = godBeastEquip.getStrengthenLevel();

            if (godBeast.getStrengthenLevel(equipPosition.getNumber()) < strengthenLevel) {
                godBeast.setStrengthenLevel(equipPosition.getNumber(), strengthenLevel);
            }
            Item.add(playerCode, CurrencyType.CT_装备, godBeastEquip.getId(), 1);
        }
        //神兽更换装备
        equipdata equipdata = DataCenter.getData(equipid, equipdata.class);
        GodBeastEquip equip = new GodBeastEquip();

        if (equipdata == null) {
            //卸下装备
            godBeast.setGodBeastEquip(equipPosition, null);
        } else {
            //修改强化等级,对应的强化属性值
            equip.setStrengthenLevel(godBeast.getStrengthenLevel(equipPosition.getNumber()));
            int attributeNum = TherionEquipHandler.getAttributeNum(godBeast, equippos, equipdata.getAttributetype(), equip.getStrengthenLevel());
            TherionEquipHandler.setAttributeValue(equip, equipdata.getAttributetype(), attributeNum);

            equip.setId(equipdata.getId());
            equip.setPosition(equipdata.getPosition());
            equip.setStar(equipdata.getStar());
            equip.setQuality(equipdata.getQuality());
            equip.setAttributetype(equipdata.getAttributetype());
            equip.setAttributenume(equipdata.getAttributenum() + attributeNum);
            equip.setSellgold(equipdata.getSellgold());
            godBeast.setGodBeastEquip(equipPosition, equip);
        }
        updataGodBeast(playerCode, godBeast);

        return Result.Success;
    }

    /**
     * 神兽战力更新
     *
     * @param playerCode
     * @param godBeast
     * @return
     */
    private boolean updataGodBeast(String playerCode, GodBeast godBeast) {
        //todo 推送战力变化
        return true;
    }

    /**
     * 神兽一键替换装备
     *
     * @param playerCode
     * @param godBeast
     * @return
     */
    public Result changeEquipFast(String playerCode, GodBeast godBeast) throws Exception {
        //寻找最佳组合
        Collection<Currency> all = new PackageHandle().getItems(playerCode, CurrencyType.CT_装备);
        HashMap<GodBeastEquipPosition, equipdata> best = new HashMap<>();
        for (Currency equip : all) {
            if (equip.getNumber() <= 0) {
                continue;
            }
            equipdata data = DataCenter.getData(equip.getDataId(), equipdata.class);
            GodBeastEquipPosition position = GodBeastEquipPosition.forNumber(data.getPosition());
            if (position == null) {
                continue;
            }
            if (!best.containsKey(position)) {
                best.put(position, data);
                continue;
            }
            //找到等级高的装备，进行替换
            equipdata equipdata = best.get(position);
            if (data.level() > equipdata.level()) {
                best.put(position, data);
            }
        }
        //依次替换
        Set<Map.Entry<GodBeastEquipPosition, equipdata>> entrySet = best.entrySet();
        for (Map.Entry<GodBeastEquipPosition, equipdata> entry : entrySet) {
            GodBeastEquipPosition position = entry.getKey(); //装备部位
            equipdata beastEquip = entry.getValue(); //最好装备
            GodBeastEquip equip = godBeast.getGodBeastEquips(position);
            //当前穿戴的装备等级和背包其他装备一样
            if (equip.getId() == beastEquip.getId()) {
                continue;
            }
            //当前穿戴的装备等级比背包其他装备等级高
            if (equip.getId() > 0) {
                equipdata godBeastEquip = DataCenter.getData(equip.getId(), equipdata.class);
                if (godBeastEquip.level() >= beastEquip.level()) {
                    continue;
                }
            }
            Item.minus(playerCode, CurrencyType.CT_装备, beastEquip.getId(), 1);
            if (equip.getId() > 0) {
                Item.add(playerCode, CurrencyType.CT_装备, equip.getId(), 1);
            }
            GodBeastEquip godBeastEquip = new GodBeastEquip();
            godBeastEquip.setId(beastEquip.getId());
            godBeastEquip.setPosition(beastEquip.getPosition());
            godBeastEquip.setStar(beastEquip.getStar());
            godBeastEquip.setQuality(beastEquip.getQuality());
            godBeastEquip.setAttributetype(beastEquip.getAttributetype());
            godBeastEquip.setAttributenume(beastEquip.getAttributenum());
            godBeastEquip.setSellgold(beastEquip.getSellgold());
            godBeast.setGodBeastEquip(position, godBeastEquip);
        }
        //推送战力变化
        updataGodBeast(playerCode, godBeast);

        return Result.Success;
    }

    public GodBeast getGodBeastById(PickedGodBeastModule pgbModule, int code) {
        GodBeast target = null;
        for (GodBeast godBeast : pgbModule.getGbs().values()) {
            if (godBeast.getCode() == code) {
                target = godBeast;
                break;
            }
        }
        return target;
    }
}

